package com.example.demo.util;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.Properties;

public class DatabaseConnectionUtil {

    /**
     * 根据传入的数据库连接信息和驱动创建数据库连接
     *
     * @param driver 数据库驱动类全限定名，如 "com.mysql.cj.driver"（MySQL）或 "oracle.jdbc.OracleDriver"（Oracle）
     * @param url    数据库连接地址，如 "jdbc:mysql://localhost:3306/your_database"（MySQL）或 "jdbc:oracle:thin:@localhost:1521:your_database"（Oracle）
     * @param username 数据库用户名
     * @param password 数据库密码
     * @return 创建好的数据库连接对象，如果创建失败则返回 null
     */
    public static Connection createConnection(String driver, String url, String username, String password) {
        try {
            // 加载驱动
            Class.forName(driver);
            // 设置连接属性
            Properties properties = new Properties();
            properties.setProperty("user", username);
            properties.setProperty("password", password);
            // 创建连接
            return DriverManager.getConnection(url, properties);
        } catch (ClassNotFoundException | SQLException e) {
            e.printStackTrace();
            return null;
        }
    }

    public static void main(String[] args) {
        // MySQL连接示例
        String mysqlDriver = "com.mysql.cj.driver";
        String mysqlUrl = "jdbc:mysql://localhost:3306/test_database";
        String mysqlUsername = "root";
        String mysqlPassword = "123456";
        Connection mysqlConnection = createConnection(mysqlDriver, mysqlUrl, mysqlUsername, mysqlPassword);
        if (mysqlConnection!= null) {
            System.out.println("成功创建MySQL数据库连接");
            try {
                mysqlConnection.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }

        // Oracle连接示例
        String oracleDriver = "oracle.jdbc.OracleDriver";
        String oracleUrl = "jdbc:oracle:thin:@localhost:1521:test_database";
        String oracleUsername = "system";
        String oraclePassword = "admin";
        Connection oracleConnection = createConnection(oracleDriver, oracleUrl, oracleUsername, oraclePassword);
        if (oracleConnection!= null) {
            System.out.println("成功创建Oracle数据库连接");
            try {
                oracleConnection.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }
}